package com.rfid.project.web;

import java.text.DateFormat;
import java.util.List;
import java.util.Date;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.data.domain.Page;

import biz.appframe.PageJsonBean;

import com.rfid.project.exception.CannotDelException;
import com.rfid.project.model.AftersaleHandleType;
import com.rfid.project.model.CommonStakeholder;
import com.rfid.project.model.DeliveryWay;
import com.rfid.project.model.People;
import com.rfid.project.model.Position;
import com.rfid.project.model.Product;
import com.rfid.project.model.Project;
import com.rfid.project.model.ProjectDeliveryType;
import com.rfid.project.model.ProjectMemberType;
import com.rfid.project.model.ProjectStakeholderType;
import com.rfid.project.model.ProjectTask;
import com.rfid.project.model.ProjectTaskType;
import com.rfid.project.service.AftersaleHandleTypeService;
import com.rfid.project.service.AftersaleRecordService;
import com.rfid.project.service.CommonStakeholderService;
import com.rfid.project.service.DeliveryWayService;
import com.rfid.project.service.PeopleService;
import com.rfid.project.service.ProcessStatus;
import com.rfid.project.service.ProductService;
import com.rfid.project.service.ProjectDeliveryTypeService;
import com.rfid.project.service.ProjectMemberService;
import com.rfid.project.service.ProjectMemberTypeService;
import com.rfid.project.service.ProjectMilestoneChangeService;
import com.rfid.project.service.ProjectMilestoneService;
import com.rfid.project.service.ProjectReportService;
import com.rfid.project.service.ProjectService;
import com.rfid.project.service.ProjectStakeholderTypeService;
import com.rfid.project.service.ProjectTaskDelayApplyService;
import com.rfid.project.service.ProjectTaskService;
import com.rfid.project.service.ProjectTaskTypeService;
import com.rfid.project.service.ProjectTaskPersonService;
import com.rfid.project.model.Department;
import com.rfid.project.service.DepartmentService;
import com.rfid.project.model.ProjectType;
import com.rfid.project.service.ProjectTypeService;
import com.rfid.project.model.ProjectSource;
import com.rfid.project.service.ProjectSourceService;
import com.rfid.project.model.Customer;
import com.rfid.project.service.CustomerService;
import com.rfid.project.model.ProjectReportFrequency;
import com.rfid.project.service.ProjectReportFrequencyService;
import com.rfid.project.util.StringUtil;

@Controller
public class ProjectController {

	private static final Logger logger = LoggerFactory
			.getLogger(ProjectController.class);

	@Autowired
	private ProjectService projectService;

	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private ProjectTypeService projectTypeService;

	@Autowired
	private ProjectSourceService projectSourceService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private ProjectReportFrequencyService projectReportFrequencyService;

	@Autowired
	private ProjectMilestoneService projectMilestoneService;
	
	@Autowired
	private PeopleService peopleService;

	@Autowired
	private ProjectMemberTypeService projectMemberTypeService;

	@Autowired
	private ProjectMemberService projectMemberService;

	@Autowired
	private ProjectStakeholderTypeService projectStakeholderTypeService;

	@Autowired
	private CommonStakeholderService commonStakeholderService;

	@Autowired
	private ProductService productService;

	@Autowired
	private ProjectTaskTypeService projectTaskTypeService;

	@Autowired
	private ProjectTaskService projectTaskService;

	@Autowired
	private AftersaleHandleTypeService aftersaleHandleTypeService;

	@Autowired
	private AftersaleRecordService aftersaleRecordService;

	@Autowired
	private ProjectReportService projectReportService;

	@Autowired
	private ProjectMilestoneChangeService projectMilestoneChangeService;

	@Autowired
	private ProjectTaskPersonService projetTaskPersonService;

	@Autowired
	private ProjectTaskDelayApplyService projectTaskDelayApplyService;

	@Autowired
	private ProjectDeliveryTypeService projectDeliveryTypeService;

	@Autowired
	private DeliveryWayService deliveryWayService;

	@RequestMapping(value = "/projectAnalyse")
	public String projectAnalyse(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		return "projectAnalyse";
	}
	
	@RequestMapping(value = "/projectOrganizationmgr")
	public String projectOrganizationmgr(HttpServletRequest request,
			HttpServletResponse response, 
			@Valid Project project, Model model) {
		model.addAttribute("project", this.projectService.findOne(project.getId()));
		
		List<ProjectTaskType> projectTaskTypes = projectTaskTypeService.findAll();
		model.addAttribute("projectTaskTypes", projectTaskTypes);
		
		Set<People> peoples = this.projectMemberService.findProjectPeoplesByProject(project);
		model.addAttribute("peoples", peoples);
		
		List<ProjectTask> projectTasks = this.projectTaskService.findByProject(project);
		model.addAttribute("projectTasks", projectTasks);
		
		model.addAttribute("projectMilestones", projectMilestoneService.findAllByProject(project));
		
		List<ProjectDeliveryType> projectDeliveryTypes = projectDeliveryTypeService.findAll();
		model.addAttribute("projectDeliveryTypes", projectDeliveryTypes);
		
		List<Product> products = productService.findAll();
		model.addAttribute("products", products);
		
		List<DeliveryWay> deliveryWays = deliveryWayService.findAll();
		model.addAttribute("deliveryWays", deliveryWays);
		
		return "projectOrganizationmgr";
	}
	@RequestMapping(value = "/projectPlanReport")
	public String projectPlanReport(HttpServletRequest request,
			HttpServletResponse response, 
			@Valid Project project, Model model) {
		model.addAttribute("project", this.projectService.findOne(project.getId()));
		
		List<ProjectTask> projectTasks = this.projectTaskService.findByProject(project);
		model.addAttribute("projectTasks", projectTasks);
		
		Set<People> peoples = this.projectMemberService.findProjectPeoplesByProject(project);
		model.addAttribute("peoples", peoples);
		
		return "projectPlanReport";
	}

	@RequestMapping(value = "/projectmgr")
	public String projectmgr(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		List<Department> departments = departmentService.findAll();
		model.addAttribute("departments", departments);

		List<ProjectType> projectTypes = projectTypeService.findAll();
		model.addAttribute("projectTypes", projectTypes);

		List<ProjectSource> projectSources = projectSourceService.findAll();
		model.addAttribute("projectSources", projectSources);

		List<Customer> customers = customerService.findAll();
		model.addAttribute("customers", customers);

		List<ProjectReportFrequency> projectReportFrequencys = projectReportFrequencyService
				.findAll();
		model.addAttribute("projectReportFrequencys", projectReportFrequencys);
		return "projectmgr";
	}

	@RequestMapping(value = "/memberProjectmgr")
	public String lookprojectmgr(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		List<Department> departments = departmentService.findAll();
		model.addAttribute("departments", departments);

		List<ProjectType> projectTypes = projectTypeService.findAll();
		model.addAttribute("projectTypes", projectTypes);

		List<ProjectSource> projectSources = projectSourceService.findAll();
		model.addAttribute("projectSources", projectSources);

		List<Customer> customers = customerService.findAll();
		model.addAttribute("customers", customers);

		List<ProjectReportFrequency> projectReportFrequencys = projectReportFrequencyService
				.findAll();
		model.addAttribute("projectReportFrequencys", projectReportFrequencys);
		return "memberProjectmgr";
	}

	@RequestMapping(value = "/queryProject")
	public String queryProject(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "projectCode", defaultValue = "") String projectCode,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "createDateBegin", defaultValue = "") Date createDateBegin,
			@RequestParam(value = "createDateEnd", defaultValue = "") Date createDateEnd,
			@RequestParam(value = "startDateBegin", defaultValue = "") Date startDateBegin,
			@RequestParam(value = "startDateEnd", defaultValue = "") Date startDateEnd,
			@RequestParam(value = "firstPlanFinishDateBegin", defaultValue = "") Date firstPlanFinishDateBegin,
			@RequestParam(value = "firstPlanFinishDateEnd", defaultValue = "") Date firstPlanFinishDateEnd,
			@RequestParam(value = "planFinishDateBegin", defaultValue = "") Date planFinishDateBegin,
			@RequestParam(value = "planFinishDateEnd", defaultValue = "") Date planFinishDateEnd,
			@RequestParam(value = "actualFinishDateBegin", defaultValue = "") Date actualFinishDateBegin,
			@RequestParam(value = "actualFinishDateEnd", defaultValue = "") Date actualFinishDateEnd,
			@RequestParam(value = "projectDescription", defaultValue = "") String projectDescription,
			@RequestParam(value = "departmentId", defaultValue = "-1") Long departmentId,
			@RequestParam(value = "projectPlanNo", defaultValue = "") String projectPlanNo,
			@RequestParam(value = "projectBatchNo", defaultValue = "") String projectBatchNo,
			@RequestParam(value = "projectTypeId", defaultValue = "-1") Long projectTypeId,
			@RequestParam(value = "projectSourceId", defaultValue = "-1") Long projectSourceId,
			@RequestParam(value = "customerId", defaultValue = "-1") Long customerId,
			@RequestParam(value = "projectReportFrequencyId", defaultValue = "-1") Long projectReportFrequencyId,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		Page<Project> items = projectService.findAll(projectCode, name,
				createDateBegin, createDateEnd, startDateBegin, startDateEnd,
				firstPlanFinishDateBegin, firstPlanFinishDateEnd,
				planFinishDateBegin, planFinishDateEnd, actualFinishDateBegin,
				actualFinishDateEnd, projectDescription, departmentId,
				projectPlanNo, projectBatchNo, projectTypeId, projectSourceId,
				customerId, projectReportFrequencyId, pageNumber, pageSize,
				sort, order);
		JSONObject object = new JSONObject();
		object.put("total", items.getTotalElements());
		JSONArray models = new JSONArray();
		for (Project item : items) {
			JSONObject mod = new JSONObject();
			wrapData(item, mod);

			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	@RequestMapping(value = "/findProject")
	public String findProject(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id,
			Model model) {
		Project project = projectService.findOne(id);
		JSONObject object = new JSONObject();
		JSONObject mod = new JSONObject();
		wrapData(project, mod);
		object.put("success", true);
		object.put("data", mod);
		PageJsonBean.printObject(response, object);
		return null;
	}
	private void wrapData(Project item, JSONObject mod) {
		mod.put("id", item.getId());
		mod.put("name", item.getName());
		mod.put("projectCode", item.getProjectCode());
		mod.put("createDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getCreateDate()));
		mod.put("startDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getStartDate()));
		mod.put("firstPlanFinishDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getFirstPlanFinishDate()));
		mod.put("planFinishDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getPlanFinishDate()));
		mod.put("planFinishDateChangeCount", item.getPlanFinishDateChangeCount());
		mod.put("actualFinishDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getActualFinishDate()));
		mod.put("projectDescription", StringUtil.getString(item.getProjectDescription()));
		mod.put("projectPlanNo", StringUtil.getString(item.getProjectPlanNo()));
		mod.put("projectBatchNo", StringUtil.getString(item.getProjectBatchNo()));
		mod.put("hardRate", item.getHardRate());

		mod.put("projectSourceID", item.getProjectSource().getId());
		mod.put("projectSourceName", item.getProjectSource().getName());

		mod.put("projectReportFrequencyID", item
				.getProjectReportFrequency().getId());
		mod.put("projectReportFrequencyName", item
				.getProjectReportFrequency().getName());

		mod.put("departmentID", item.getDepartment().getId());
		mod.put("departmentName", item.getDepartment().getName());

		mod.put("projectTypeID", item.getProjectType().getId());
		mod.put("projectTypeName", item.getProjectType().getName());

		mod.put("customerID", item.getCustomer().getId());
		mod.put("customerName", item.getCustomer().getName());
		mod.put("status", ProcessStatus.processStatusName(item.getStatus()));
		mod.put("statusCode", item.getStatus());
		
		mod.put("planConsumeWorkTime", item.getPlanConsumeWorkTime());
		Float sum = item.getActualConsumeWorktime();
		mod.put("actualConsumeWorktime", sum);
		float peopleAverage = 0;
		if(null != sum){
			peopleAverage = sum / 8;
		}
		mod.put("peopleAverage", com.rfid.project.util.StringUtil.getString(peopleAverage, ".", 3));
	}

	@RequestMapping(value = "/lookProjectDetail")
	public String lookProjectDetail(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model) {
		Project project = this.projectService.findOne(id);
		model.addAttribute("project", project);
		
		model.addAttribute("projectMilestones", this.projectMilestoneService.findAllByProject(project));

		Set<People> createPersons = this.projectMemberService.findCreateProjectPeoplesByProject(project);
		model.addAttribute("createProjectPeoples", createPersons);
		Set<People> projectPersons = this.projectMemberService.findProjectPeoplesByProject(project);
		model.addAttribute("projectPersons", projectPersons);

		List<ProjectMemberType> projectMemberTypes = projectMemberTypeService
				.findAll();
		model.addAttribute("projectMemberTypes", projectMemberTypes);
		
		List<ProjectStakeholderType> projectStakeholderTypes = projectStakeholderTypeService.findAll();
		model.addAttribute("projectStakeholderTypes", projectStakeholderTypes);

		List<Product> products = productService.findAll();
		model.addAttribute("products", products);

		List<ProjectTaskType> projectTaskTypes = projectTaskTypeService
				.findAll();
		model.addAttribute("projectTaskTypes", projectTaskTypes);
		
		Set<People> createProjectTaskPeoples = this.projectTaskService.findCreatePeoplesByProjectTask(project);
		model.addAttribute("createProjectTaskPeoples", createProjectTaskPeoples);

		List<Customer> customers = customerService.findAll();
		model.addAttribute("customers", customers);

		List<AftersaleHandleType> aftersaleHandleTypes = aftersaleHandleTypeService
				.findAll();
		model.addAttribute("aftersaleHandleTypes", aftersaleHandleTypes);
		
		model.addAttribute("aftersaleHandleRegisterPersons", this.aftersaleRecordService.findRegisterPersonByProject(project));
		model.addAttribute("aftersaleHandleCheckPersons", this.aftersaleRecordService.findCheckPersonsByProject(project));
		model.addAttribute("aftersaleHandleHandlePersons", this.aftersaleRecordService.findHandlePersonsByProject(project));
		model.addAttribute("aftersaleHandleCustomers", this.aftersaleRecordService.findCustomer(project));
		
		model.addAttribute("projectResportPeoples", this.projectReportService.findPeoplesByProject(project));
		
		model.addAttribute("projectMilestoneApplyPeoples", this.projectMilestoneChangeService.findApplyPersonsByProject(project));
		model.addAttribute("projectMilestoneCheckPeoples", this.projectMilestoneChangeService.findCheckPersonsByProject(project));
		
		return "projectDetail";
	}
	
	@RequestMapping(value = "/editProjectDetail")
	public String editProjectDetail(
			HttpServletRequest request,
			HttpServletResponse response,
			@Valid Project project,
			Model model) {
		model.addAttribute("project", project);
		model.addAttribute("peoples", this.peopleService.findAll());

		Set<People> createPersons = this.projectMemberService.findCreateProjectPeoplesByProject(project);
		model.addAttribute("createProjectPeoples", createPersons);
		
		List<People> projectPersons = this.peopleService.findAll();
		model.addAttribute("projectMembers", projectPersons);
		
		List<ProjectMemberType> projectMemberTypes = this.projectMemberTypeService.findAll();
		model.addAttribute("projectMemberTypes", projectMemberTypes);
		
		List<Product> products = productService.findAll();
		model.addAttribute("products", products);
		
		List<ProjectStakeholderType> projectStakeholderTypes = projectStakeholderTypeService.findAll();
		model.addAttribute("projectStakeholderTypes", projectStakeholderTypes);
		
		//常用关系人
		List<CommonStakeholder> commonStakeholders = this.commonStakeholderService.findByProjectStakeholderType(ProjectStakeholderType.GROUP_Purchase, ProjectStakeholderType.GROUP_PRODUCTION, ProjectStakeholderType.GROUP_PLAN);
		model.addAttribute("commonStakeholders", commonStakeholders);
		//项目干系人
		List<People> projectStakeholderPeoples = this.peopleService.findByPostionIds(Position.COMPANY_MANAGER_ID, Position.PLAN_ID, Position.QUALITY_ID);
		model.addAttribute("projectStakeholderPeoples", projectStakeholderPeoples);
		
		
		return "editProjectDetail";
	}

	@RequestMapping(value = "/editProject", method = RequestMethod.POST)
	public String editProject(HttpServletRequest request,
			HttpServletResponse response, @Valid Project project, Model model,
			RedirectAttributes redirectAttributes) {
		boolean flag = false;
		if(null != project){
			projectService.saveProject(project);
			flag = true;
		}
		JSONObject result = new JSONObject();
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/delProject")
	public String delProject(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			this.projectService.deleteProject(id);
		} catch (CannotDelException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/pullDownProject")
	public String pullDownProject(HttpServletRequest request,
			HttpServletResponse response,
			@Valid Project project) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		this.projectService.pullDownProject(project);
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		DateFormat dateFormat = com.rfid.project.util.DateUtil
				.getFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

}
